<?php
/**
 * Class member_levelModel
 * 开发平台授权登录表
 * @version 1.0
 */
defined('InShopNC') or exit('Access Invalid!');
class member_oauthModel extends Model{
    public function __construct(){
        parent::__construct('member_oauth');
    }

    /**
     * 获取绑定的用户信息
     * @param array $oauth_info
     * @return null|array
     */
    public function getBindInfo(array $oauth_info){
        $oauth_form=$oauth_info['oauth_form'];
        $openid=$oauth_info['openid'];
        $result=$this->where(compact('oauth_form','openid'))->find();
        if($result){
            $result['oauth_info']=unserialize($result['oauth_info']);
        }
        return $result;
    }

    /**
     * 绑定授权信息
     * @param string|int $member_id
     * @param array $oauth_info
     * @return mixed
     */
    public function bindOauth($member_id,array $oauth_info){
        $os=$this->getBindInfo($oauth_info);
        $oauth_info['updated_at']=$oauth_info['created_at']=time();
        $oauth_info['member_id']=$member_id;
        $oauth_info['oauth_info']=is_string($oauth_info['oauth_info'])?$oauth_info['oauth_info']:serialize($oauth_info);
        if($os){
            if($os['member_id']!=$member_id)return false;
            return $this->update($oauth_info,array('oauth_form'=>$oauth_info['oauth_form'],'member_id'=>$member_id));
        }else{
            return $this->insert($oauth_info);
        }
    }

    /**
     * 刷新绑定的授权信息
     * @param string|int $member_id
     * @param array $oauth_info
     * @return bool
     */
    public function refreshOauth($member_id,array $oauth_info){
        $oauth_info['oauth_info']=is_string($oauth_info['oauth_info'])?$oauth_info['oauth_info']:serialize($oauth_info);
        $oauth_info['oauth_num']=array('exp','`oauth_num`+1');
        $oauth_info['updated_at']=time();
        $oauth_form=$oauth_info['oauth_form'];
        return $this->update($oauth_info,array('where'=>compact('oauth_form','member_id')));
    }

    /**
     * 解除绑定的授权信息
     * @param $member_id
     * @param $oauth_form
     * @return bool
     */
    public function unbind($member_id,$oauth_form){
        return $this->delete(array(compact('member_id','oauth_form')));
    }
}